package com.qianbao.qianbaobusiness.ui.cashier;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidbase.utils.AndroidUtils;
import com.androidbase.utils.ToastUtils;
import com.androidbase.widget.recycleadpter.BaseRecycleViewAdapter;
import com.baseandroid.config.Constant;
import com.baseandroid.config.Global;
import com.baseandroid.mvp.BaseMvpActivity;
import com.baseandroid.utils.MoneyUtil;
import com.baseandroid.utils.TimeUtils;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.help.DateTimePickDialogHelper;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.json.SettlementDetailBean;

import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SummaryBalanceActivity extends BaseMvpActivity<SummaryBalanceView, SummaryBalancePresenter> implements SummaryBalanceView, DatePickerDialog.OnDateSetListener, SwipeRefreshLayout.OnRefreshListener, BaseRecycleViewAdapter.OnLoadMoreListener {
    /**
     * 控件相关
     */
    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.right_image)
    ImageView rightImage;
    @BindView(R.id.start_layout)
    LinearLayout startLayout;
    @BindView(R.id.start_time)
    TextView mTvStart;
    @BindView(R.id.tv_start_time)
    TextView mTextTvStartTime;
    @BindView(R.id.tv_end_time)
    TextView mTextTvEndTime;
    @BindView(R.id.end_layout)
    LinearLayout endLayout;
    @BindView(R.id.end_time)
    TextView mTvEnd;
    @BindView(R.id.swip_history)
    SwipeRefreshLayout mSwrl;
    @BindView(R.id.recy_history)
    RecyclerView recyHistory;
    @BindView(R.id.tv_all_income_money)
    TextView mTvAllIncomeMoney;
    @BindView(R.id.ll_uplayout)
    LinearLayout ll_uplayout;

    private String mStartDate;     //默认开始日期
    private String mEndDate;   //默认的结束日期
    private boolean isStart = true;
    private LinearLayoutManager mLayoutManager;
    private SettlementAdapter mRvAdapter;
    private String PosMerchantNo;      //请求需要cod
    private PopupWindow popupWindow;   //邮箱发送弹框
    private int pageNum = 1;
    private static final int PAGE_SIZE = 15;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_summary_balance;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        PosMerchantNo = getSelectedPosMerchantNo();
        mStartDate = TimeUtils.getDateNDaysDelay(-11, Constant.DATE_YYYY_MM_DD);
        mTvStart.setText(mStartDate);
        mTextTvStartTime.setText(mStartDate);
        mEndDate = TimeUtils.getDateNDaysDelay(0, Constant.DATE_YYYY_MM_DD);
        mTvEnd.setText(mEndDate);
        mTextTvEndTime.setText(mEndDate);
        mSwrl.setOnRefreshListener(this);
        mSwrl.setColorSchemeColors(ContextCompat.getColor(this, R.color.text_red));
        mRvAdapter = new SettlementAdapter(this);
        mLayoutManager = new LinearLayoutManager(this);
        recyHistory.setLayoutManager(mLayoutManager);
        recyHistory.setAdapter(mRvAdapter);
        mRvAdapter.setOnLoadMoreListener(this, recyHistory);
    }

    private String getSelectedPosMerchantNo() {
        String posMerchantNos = "";
        List<MerchantInfo> merchantList = Global.getSelectedShopListInfo().merchantList;
        if (merchantList == null || merchantList.size() == 0) {
            return posMerchantNos;
        } else {
            for (MerchantInfo merchantInfo : merchantList) {
                if (merchantInfo.isSelected) {
                    if (TextUtils.isEmpty(posMerchantNos)) {
                        posMerchantNos = merchantInfo.posMerchantNo;
                    } else {
                        posMerchantNos = posMerchantNos + "," + merchantInfo.posMerchantNo;
                    }
                }
            }
            return posMerchantNos;
        }
    }

    private String getSelectedMerchantNos() {
        StringBuilder sb = new StringBuilder();
        for (MerchantInfo merchantInfo : Global.getSelectedShopListInfo().merchantList) {
            if (merchantInfo.isSelected) {
                sb.append(merchantInfo.merchantNo).append(",");
            }
        }
        String merchantNos;
        if (!TextUtils.isEmpty(sb)) {
            merchantNos = sb.substring(0, sb.indexOf(","));
        } else {
            merchantNos = "";
        }
        return merchantNos;
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        toolbarTitle.setText("结算汇总");
        rightImage.setVisibility(View.VISIBLE);
        pageNum = 1;
        getDatas();
    }

    private void getDatas() {
        getPresenter().queryColtCheckedPage(PosMerchantNo, pageNum, PAGE_SIZE, mTvStart.getText()
                .toString()
                .replaceAll("-", ""), mTvEnd.getText().toString().replaceAll("-", ""));
    }

    @OnClick({R.id.toolbar_back, R.id.right_image, R.id.start_layout, R.id.end_layout})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:    //返回操作
                finish();
                break;

            case R.id.right_image:     //发送邮箱
                SendEmailPopWindow morePopWindow = new SendEmailPopWindow(SummaryBalanceActivity.this, ll_uplayout, TimeUtils
                        .getDate(mStartDate, Constant.DATE_YYYY_MM_DD, Constant.DATE_YYYYMMDD), TimeUtils
                        .getDate(mEndDate, Constant.DATE_YYYY_MM_DD, Constant.DATE_YYYYMMDD), "2", new SendEmailPopWindow.onItmeclick() {
                    @Override
                    public void onItemClickListern() {
                        if (TextUtils.isEmpty(Global.getUserInfoBean()
                                .getUser()
                                .getEmail())) {
                            ToastUtils.showLongToast(AndroidUtils.getContext()
                                    .getResources()
                                    .getString(R.string.dont_bind_emile));
                        } else {
                            getPresenter().sendEmail(Constant.HISTORY_TYPE, TimeUtils.getDate(mStartDate, Constant.DATE_YYYY_MM_DD, Constant.DATE_YYYYMMDD), TimeUtils
                                    .getDate(mEndDate, Constant.DATE_YYYY_MM_DD, Constant.DATE_YYYYMMDD), getSelectedMerchantNos(), Global
                                    .getUserInfoBean()
                                    .getUser()
                                    .getUserNo(), Global.getUserInfoBean()
                                    .getUser()
                                    .getEmail());
                        }
                    }
                });
                morePopWindow.showPopupWindow(morePopWindow, rightImage);
                morePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        ll_uplayout.setVisibility(View.GONE);
                    }
                });


                break;

            case R.id.start_layout:  //开始日期选择
                isStart = true;
                new DateTimePickDialogHelper(this).addDatePickListern(new DateTimePickDialogHelper.TimePickListener() {
                    @Override
                    public void date(String date) {
                        mStartDate = date;
                        judgeDate();
                    }
                }).show(getCalendar(mTvStart.getText().toString()));
                break;

            case R.id.end_layout:  //结束日期选择
                isStart = false;
                new DateTimePickDialogHelper(this).addDatePickListern(new DateTimePickDialogHelper.TimePickListener() {
                    @Override
                    public void date(String date) {
                        mEndDate = date;
                        judgeDate();
                    }
                }).show(getCalendar(mTvEnd.getText().toString()));
                break;
            default:
                break;
        }
    }

    private Calendar getCalendar(String s) {
        Calendar calendar = Calendar.getInstance();
        String[] arr = s.split("-");
        calendar.set(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]) - 1, Integer.parseInt(arr[2]));
        return calendar;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        if (isStart) {    //因为这里的开始时间和结束时间用的是同一个DatePicker,所以用来加以区分
            mStartDate = year + "-" + (month < 9 ? "0" + ++month : month) + "-" + (dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth);
        } else {
            mEndDate = year + "-" + (month < 9 ? "0" + ++month : month) + "-" + (dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth);
        }
    }

    private void judgeDate() {
        int numOfDaysStart2Default = TimeUtils.getNumOfDays(mStartDate, Constant.BALANCE_DEFAULT_DAY, Constant.DATE_YYYY_MM_DD);
        int numOfDaysStart2Month = TimeUtils.getNumOfDays(mStartDate, TimeUtils.beforeMothDate(-6, Constant.DATE_YYYY_MM_DD), Constant.DATE_YYYY_MM_DD);
        int numOfDaysStart2End = TimeUtils.getNumOfDays(mStartDate, mEndDate, Constant.DATE_YYYY_MM_DD);
        int numOfDaysEnd = TimeUtils.getNumOfDays(mEndDate, TimeUtils.getDateNDaysDelay(0, Constant.DATE_YYYY_MM_DD), Constant.DATE_YYYY_MM_DD);
        if (isStart) {
            if (numOfDaysStart2Default > 0) {   //账单查询不能早于2017-01-01
                ToastUtils.showLongToast(getApplicationContext().getResources()
                        .getString(R.string.only_check_to_2017));
                return;
            }
            if (numOfDaysStart2Month > 0) {     //查询账单不能早于半年前
                ToastUtils.showLongToast(getApplicationContext().getResources()
                        .getString(R.string.check_half_year));
                return;
            }
            if (numOfDaysStart2End < 0) {   //开始时间不能小于结束时间
                ToastUtils.showLongToast(getApplicationContext().getResources()
                        .getString(R.string.start_dont_after_end));
                return;
            }
            mTvStart.setText(mStartDate);
            pageNum = 1;
            getDatas();
        } else {
            if (numOfDaysEnd < 0) {
                ToastUtils.showLongToast("结束时间不能大于今日");
                return;
            }
            if (numOfDaysStart2End <= 0) {   //开始时间不能小于结束时
                ToastUtils.showLongToast(getApplicationContext().getResources()
                        .getString(R.string.end_dont_before_end));
                return;
            }
            mTvEnd.setText(mEndDate);
            pageNum = 1;
            getDatas();
        }
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        getDatas();
    }

    @Override
    public void onError(Throwable e) {
        if (mSwrl.isRefreshing()) {
            mSwrl.setRefreshing(false);
        } else {
            mRvAdapter.loadMoreFail();
        }
    }

    @Override
    public void onSuccess(SettlementDetailBean bean) {
        if (bean.getTotalmoney() != null && !bean.getTotalmoney().equals("")) {
            String s = Double.parseDouble(bean.getTotalmoney()) / 100 + "";
            s = MoneyUtil.getMoneyFormat(s);
            mTvAllIncomeMoney.setText(getResources().getString(R.string.rmb) + s);
        } else {
            mTvAllIncomeMoney.setText(getResources().getString(R.string.rmb) + "0.00");
        }
        mTextTvStartTime.setText(mStartDate);
        mTextTvEndTime.setText(mEndDate);
        if (mSwrl.isRefreshing()) {
            mSwrl.setRefreshing(false);
        }
        if (bean.getList() == null) {
            return;
        }
        if (pageNum == 1) {
            if (bean.getList().size() == 0) {
                mRvAdapter.setEmptyView(R.layout.layout_empty_balance);
                // mRvAdapter.loadMoreEnd(false);
            } else if (bean.getList().size() < PAGE_SIZE) {
                mRvAdapter.resetData(bean.getList());
                recyHistory.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRvAdapter.loadMoreEnd(true);
                    }
                }, 200);

            } else {
                mRvAdapter.resetData(bean.getList());
                mRvAdapter.loadMoreComplete();
            }
        } else {
            if (bean.getList().size() == 0) {
                mRvAdapter.loadMoreEnd(false);
                return;
            }
            if (bean.getList().size() < PAGE_SIZE) {
                mRvAdapter.addData(bean.getList());
                mRvAdapter.loadMoreEnd(false);
                return;
            }
            mRvAdapter.addData(bean.getList());
            mRvAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        getDatas();
    }
}
